package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Author LEO
 * @Date 2021年12月21日 20:05
 */
//接收消息   消费消息测试类
@Component
public class ConfirmReceiver {
    //监听获取消息  设置绑定关系
    @SneakyThrows //处理异常
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.confirm",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "exchange.confirm",durable = "true",autoDelete = "false"),
            key = {"routing.confirm"}
      ))
    public void getMsg(String msg, Message message, Channel channel){
        try {
            System.out.println("接收的消息：\t"+new String(message.getBody()));
            System.out.println("接收到的消息：\t"+msg);
            //手动确认 ack
            long deliverTag =message.getMessageProperties().getDeliveryTag();
            // false : 表示一个一个的确认，true 表示批量确认消息
            channel.basicAck(deliverTag,false);
        } catch (IOException e) {
            e.printStackTrace();
            //log.info(".....")
            //第三个参数。是否回归队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }


    // 测试死信 消费消息  监听死信队列
    @SneakyThrows //处理异常
    @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    public void getMsg2(String msg, Message message, Channel channel){
        //需要知道系统当前时间 接收时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("接收到的消息： \t"+msg+"时间"+sdf.format(new Date()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  消费消息  监听   基于插件
    @SneakyThrows //处理异常
    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    public void getMsg3(String msg, Message message, Channel channel){
        //需要知道系统当前时间 接收时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("接收到的消息： \t"+msg+"时间"+sdf.format(new Date()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
